<template>
  <div>
    <el-upload
      ref="upload"
      class="upload-demo"
      drag
      multiple
      :limit="9"
      :auto-upload="false"
      action="/upload"
      list-type="picture"
      :file-list="uploadList"
      :on-preview="onIcoPreview"
      :on-remove="onIcoRemove"
      :before-upload="onIcoBeforeUpload"
      :on-change="onIcoChange"
      :on-error="onIcoErr"
      :on-success="onIcoSuc"
      :on-progress="onIcoProgress"
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">
        将文件拖到此处，或
        <em>点击上传</em>
      </div>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
    </el-upload>
  </div>
</template>

<script>
import to from 'await-to-js';
export default {
  data() {
    return {
      uploadList: [],
    };
  },
  methods: {
    onIcoProgress(event, file, fileList) {
      console.log('onIcoProgress: ', event, file, fileList);
    },
    onIcoSuc(response, file, fileList) {
      console.log('onIcoSuc: ', response, file, fileList);
    },
    onIcoErr(err, file, fileList) {
      console.log('onIcoErr: ', err, file, fileList);
    },
    onIcoPreview(file) {
      console.log('onIcoPreview: ', file);
    },
    onIcoRemove(file, fileList) {
      console.log('onIcoRemove: ', file, fileList);
    },
    async onIcoChange(file, fileList) {
      const [err, ratio] = await to(this.imgSizeRatioByFileReader(file, 1920, 1080));
      console.log('onIcoChange: ', file, fileList, err, ratio, this.uploadList);

      if (err) {
        // this.$refs.upload.clearFiles();
        this.$message.error('出错了，请重试~');
        return false;
      }
      if (!ratio.isMatch) {
        this.uploadList = this.uploadList.filter((val) => val.name != file.name);
        this.$message.error('图片比例应为1920*1080~');
        return Promise.reject(false);
      }
    },
    async onIcoBeforeUpload(file) {
      const [err, ratio] = await to(this.imgSizeRatio(file, 1920, 1080));
      console.log('onIcoBeforeUpload: ', file, err, ratio);
      if (err) {
        // this.$refs.upload.clearFiles();
        this.$message.error('出错了，请重试~');
        return false;
      }
      if (!ratio.isMatch) {
        this.uploadList = this.uploadList.filter((val) => val.name != file.name);
        this.$message.error('图片比例应为1920*1080~');
        return false;
      }
    },
    imgSizeRatio(file, width, height) {
      return new Promise((resolve, reject) => {
        const _URL = window.URL || window.webkitURL;
        const url = _URL.createObjectURL(file);
        const img = new Image();
        img.src = url;
        img.onload = () => {
          const _width = img.width,
            _height = img.height;
          resolve({ width, height, ratio: width / height, isMatch: width * _height === height * _width });
          console.log('imgSizeRatio: ', file, url, width, height, _width, _height, width * _height === height * _width);
        };
        img.onerror = () => {
          reject('Image onload error!');
        };
      });
    },
    imgSizeRatioByFileReader(file, width, height) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file.raw); // 必须用file.raw
        reader.onload = () => {
          const img = new Image();
          img.src = reader.result;
          if (img.complete) {
            const _width = img.width,
              _height = img.height;
            resolve({ file, width, height, ratio: width / height, isMatch: width * _height === height * _width });
            console.log(
              'complete imgSizeRatio: ',
              file,
              width,
              height,
              _width,
              _height,
              width * _height === height * _width
            );
          } else {
            img.onload = () => {
              const _width = img.width,
                _height = img.height;
              resolve({ file, width, height, ratio: width / height, isMatch: width * _height === height * _width });
              console.log(
                'onload imgSizeRatio: ',
                file,
                width,
                height,
                _width,
                _height,
                width * _height === height * _width
              );
            };
            img.onerror = () => {
              reject('Image onload error!');
            };
          }
        };
      });
    },
    /*
      覆盖默认的上传行为，可以自定义上传的实现
      http-request="onRequest"
    */
    onRequest() {
      console.log('uploader request');
    },
  },
};
</script>

<style></style>
